import 'dart:async';

import 'package:day_demo/src/long_image_cliper/image_clipper.dart';
import 'package:flutter/material.dart';

class ClipperImageContainer extends StatefulWidget {
  const ClipperImageContainer({
    super.key,
    required this.imageProvider,
    required this.width,
    required this.height,
    this.x = 0,
    this.y = 0,
    this.ratio = 0.75,
  });
  final double width;
  final double height;
  final double x;
  final double y;
  final double ratio;
  final ImageProvider imageProvider;
  @override
  State<ClipperImageContainer> createState() => _ClipperImageContainerState();
}

class _ClipperImageContainerState extends State<ClipperImageContainer> {
  ImageClipper? clipper;
  @override
  void initState() {
    _getImage();
    super.initState();
  }

  Future<ImageInfo> getImageInfoByProvider(ImageProvider provider) {
    final Completer<ImageInfo> completer = Completer();
    bool flag = false;
    provider
        .resolve(const ImageConfiguration())
        .addListener(ImageStreamListener((info, _) {
      if (!flag) {
        completer.complete(info);
        flag = true;
      }
    }));
    return completer.future;
  }

  void _getImage() async {
    final imageInfo = await getImageInfoByProvider(widget.imageProvider);
    clipper = ImageClipper(imageInfo.image,
        x: widget.x, y: widget.y, ratio: widget.ratio);
    setState(() {});
  }

  @override
  void dispose() {
    clipper = null;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      painter: clipper,
      size: Size(widget.width, widget.height),
    );
  }
}
